package com.cctc.mychat.server.handler.Message;

import com.cctc.mychat.common.protocol.message.impl.request.LoginRequestMessage;
import com.cctc.mychat.common.protocol.message.impl.response.LoginResponseMessage;
import com.cctc.mychat.common.session.Session;
import com.cctc.mychat.common.session.SessionManager;
import com.cctc.mychat.common.util.JsonUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage request) throws Exception {
        System.out.println("[LoginRequestMessageHandler] 登录消息：" + JsonUtils.toJson(request));

        String userName = request.getUserName();
        LoginResponseMessage response = LoginResponseMessage.builder().userName(userName).build();
        if (valid(request)) {
            Session session = Session.builder().userName(userName).build();
            SessionManager.bindSession(session, ctx.channel());
            response.setSuccess(true);
            System.out.println("[LoginRequestMessageHandler] 登录成功！！！");
        } else {
            response.setSuccess(false);
            String reason = "{用户名&密码} 校验失败！！！";
            response.setReason(reason);
            System.err.println("[LoginRequestMessageHandler] 登录失败，原因：" + reason);
        }

        ctx.writeAndFlush(response);
    }

    private boolean valid(LoginRequestMessage request) {
        return true;
    }
}
